using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AutoGear.BLL;
using System.Collections.Generic;
using System.IO;
using Entity;
using ECommerce.Library;
using ECommerce.Library.DataStructure;
using ECommerce.Library.ECommerce;
using eShop.Model;
using eShop.DataAccess;
using eShop.Business;

public partial class admin_product_edit : SiteAdminBasePage
{
    private Int32 _ProductId
    {
        get
        {
            return Convert.ToInt32(Request.QueryString["pid"]);
        }
    }

    private List<Decimal> DeleteList
    {
        get
        {
            try
            {
                if (HttpContext.Current.Session["_DeleteList"] != null)
                {
                    return HttpContext.Current.Session["_DeleteList"] as List<Decimal>;
                }
                else
                {
                    List<Decimal> _DeleteList = new List<Decimal>();
                    HttpContext.Current.Session["_DeleteList"] = _DeleteList;
                    return _DeleteList;
                }
            }
            catch
            {
                List<Decimal> _DeleteList = new List<Decimal>();
                HttpContext.Current.Session["_DeleteList"] = _DeleteList;
                return _DeleteList;
            }
        }
        set
        {
            HttpContext.Current.Session["_DeleteList"] = value;
        }
    }
    private ECommerce.DAL.CustomCollection<ProductPartner> partnerProducts
    {
        get
        {
            return HttpContext.Current.Session["_partnerProducts"] as ECommerce.DAL.CustomCollection<ProductPartner>;
        }
        set
        {
            HttpContext.Current.Session["_partnerProducts"] = value;
        }
    }

    private ECommerce.DAL.CustomCollection<Manufacturer> brands
    {
        get
        {
            return HttpContext.Current.Session["_brands"] as ECommerce.DAL.CustomCollection<Manufacturer>;
        }
        set
        {
            HttpContext.Current.Session["_brands"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CleanAllSession();
            LoadDropDowns();
            LoadData();
            LoadPartners();
        }
    }

    private void CleanAllSession()
    {
        HttpContext.Current.Session["_brands"] = null;
        HttpContext.Current.Session["_partnerProducts"] = null;
        HttpContext.Current.Session["_DeleteList"] = null;
    }

    private void LoadPartners()
    {
        partnerProducts = TblPartnerProduct.GetAllTblPartnerProductByProductId(_ProductId);
        brands = ManufacturerManager.Brands(true);
        brands.Add(new Manufacturer(-1, "Select", "", "", "", true, string.Empty));
        repProductPartners.DataSource = partnerProducts;
        repProductPartners.DataBind();
    }

    private void LoadData()
    {
        int productId = 0;
        if (!string.IsNullOrEmpty(Request.QueryString["pid"]) &&
            int.TryParse(Request.QueryString["pid"], out productId))
        {
            Product product = Product.Load(productId);
            BindData(product);
            BindAdditionalProductData(product.ProductId);
        }
    }

    private void BindAdditionalProductData(int productId)
    {
        IList<TblProductAdditionalImage> additionals = TblProductAdditionalImage.GetTblProductAdditionalImageByProductID(productId);

        rptAdditionalPreview.DataSource = additionals;
        rptAdditionalPreview.DataBind();
        if (additionals != null && additionals.Count > 0)
        {
            divAdditionalPreviews.Visible = true;
        }
    }

    private void BindData(Product product)
    {
        if (product != null)
        {
            tbxProductName.Text = product.ProductName;
            tbxProductName2.Text = product.ProductName2;
            ddlParent.SelectedValue =Server.HtmlDecode(product.Category.CategoryId.ToString());
            //ddlBrand.SelectedValue = product.Brand.ProductBrandId.ToString();
            tbxDisplayOrder.Text = product.DisplayOrder;
            hidRecipies.Value = Server.HtmlDecode(product.Recipies);
            hidAdditionalInfo.Value= Server.HtmlDecode(product.AdditionalInfo);
            tbxPrice.Text = product.ProductActualPrice.ToString();
            tbxRetailPrice.Text = product.RetailPrice.ToString();
            tbxCurrentCost.Text = product.CurrentCost.ToString();
            tbxStandardCost.Text = product.StandardCost.ToString();
            tbxItemNumber.Text = product.ItemNumber;
            //tbxDescription.Text = Server.HtmlDecode(product.ProductDescription).Replace("<br />", "\r\n");
            hidDescription.Value = Server.HtmlDecode(product.ProductDescription);
            hidTechnicalSpec.Value = Server.HtmlDecode(product.AdditionalPriceDesc);
            cbxIsActive.Checked = product.IsActive;
            cbxFeatured.Checked = product.IsFeatured;
            cbxSpecial.Checked = product.IsSpecial;
            imgProductDefaultImagePreview.ImageUrl = ImageResizer.CheckImageMissing(product.ProductImageLargeThumbnail, string.Empty);
            divProductDefaultImagePreview.Visible = string.IsNullOrEmpty(imgProductDefaultImagePreview.ImageUrl) ? false : true;
            try
            {
                ProductStock stock = product.Stocks[0];
                tbxWidthWholeFirstDigit.Text = stock.WidthWholeNumberFirstDigit.ToString();
                tbxWidthWholeSecondDigit.Text = stock.WidthWholeNumberSecondDigit.ToString();
                tbxWidthFractionFirstDigit.Text = stock.WidthFractionNumberFirstDigit.ToString();
                tbxWidthFractionSecondDigit.Text = stock.WidthFractionNumberSecondDigit.ToString();
                tbxDiameterWholeFirstDigit.Text = stock.DiameterWholeNumberFirstDigit.ToString();
                tbxDiameterWholeSecondDigit.Text = stock.DiameterWholeNumberSecondDigit.ToString();
                tbxDiameterFractionFirstDigit.Text = stock.DiameterFractionNumberFirstDigit.ToString();
                tbxDiameterFractionSecondDigit.Text = stock.DiameterFractionNumberSecondDigit.ToString();
                tbxThreadCountWholeFirstDigit.Text = stock.ThreadCountWholeNumberFirstDigit.ToString();
                tbxThreadCountWholeSecondDigit.Text = stock.ThreadCountWholeNumberSecondDigit.ToString();
                tbxThreadCountFractionFirstDigit.Text = stock.ThreadCountFractionNumberFirstDigit.ToString();
                tbxThreadCountFractionSecondDigit.Text = stock.ThreadCountFractionNumberSecondDigit.ToString();
                tbxLengthWholeFirstDigit.Text = stock.LengthWholeNumberFirstDigit.ToString();
                tbxLengthWholeSecondDigit.Text = stock.LengthWholeNumberSecondDigit.ToString();
                tbxLengthFractionFirstDigit.Text = stock.LengthFractionNumberFirstDigit.ToString();
                tbxLengthFractionSecondDigit.Text = stock.LengthFractionNumberSecondDigit.ToString();
                tbxSize.Text = stock.Size;
                tbxWeight.Text = stock.Weight.ToString();
                tbxWeightUnit.Text = stock.WeightUnit.ToString();
                tbxStock.Text = stock.StockAmount.ToString();
                tbxPkgQuanity.Text = stock.PkgQuanity.ToString();
            }
            catch { }
        }
    }

    protected void Create_Click(object sender, EventArgs e)

    {
        try
        {
            if (IsValid)
            {
                bool imageUploaded = false;
                string tempImageFolder = string.Empty;
                if (fluProductDefaultImage.HasFile)
                {
                    tempImageFolder = SiteUtility.TempFolder + fluProductDefaultImage.FileName;

                    if (File.Exists(MapPath(tempImageFolder)))
                        FileAccessUtility.DeleteFile(tempImageFolder);

                    string contentType = fluProductDefaultImage.PostedFile.ContentType.ToLower();
                    if (contentType == "image/jpg" || contentType == "image/gif" || contentType == "image/png"
                        || contentType == "image/jpeg" || contentType == "image/bmp" || contentType == "image/pjpeg"
                        || contentType == "image/x-png")
                    {
                        fluProductDefaultImage.SaveAs(MapPath(tempImageFolder));
                        imageUploaded = true;
                    }
                    else
                    {
                        uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ImageFormateNotSupported);
                    }
                }

                int productId = 0;
                if (!string.IsNullOrEmpty(Request.QueryString["pid"]) &&
                    int.TryParse(Request.QueryString["pid"], out productId))
                {
                    Product product = Product.Load(productId);

                    if (product != null)
                    {
                        try
                        {
                            if (product.ProductName != tbxProductName.Text)
                                product.ProductName = tbxProductName.Text;
                            if (product.ProductName2 != tbxProductName2.Text)
                                product.ProductName2 = tbxProductName2.Text;

                            product.ProductDescription = hidDescription.Value.Trim();
                            if (ddlParent.SelectedValue != product.Category.CategoryId.ToString())
                                product = Product.ChangeCategory(product, CategoryManager.Load(Convert.ToInt32(ddlParent.SelectedValue)));

                            //product.Brand = ProductBrand.Load(Convert.ToInt32(ddlBrand.SelectedValue));
                            product.DisplayOrder = Security.BindStringInput(tbxDisplayOrder.Text, SecurityLevel.Zero);
                            product.ProductActualPrice = Security.BindDoubleInput(tbxPrice.Text, SecurityLevel.Zero);
                            product.RetailPrice = Security.BindDoubleInput(tbxRetailPrice.Text,SecurityLevel.Zero);
                            product.CurrentCost = Security.BindDoubleInput(tbxCurrentCost.Text, SecurityLevel.Zero);
                            product.StandardCost = Security.BindDoubleInput(tbxStandardCost.Text, SecurityLevel.Zero);
                            product.AdditionalPrice = Security.BindDoubleInput(tbxAdditionalPrice.Text, SecurityLevel.Zero);
                            product.AdditionalPriceDesc = Security.BindStringInput(hidTechnicalSpec.Value.Trim(), SecurityLevel.Zero);
                            product.Recipies = hidRecipies.Value.Trim();
                            product.AdditionalInfo =hidAdditionalInfo.Value.Trim() ;
                            product.ItemNumber = Security.BindStringInput(tbxItemNumber.Text, SecurityLevel.Zero);
                            product.IsFeatured = cbxFeatured.Checked;
                            product.IsActive = cbxIsActive.Checked;
                            product.IsSpecial = cbxSpecial.Checked;
                            
                            ProductStock stock = product.Stocks[0];

                            stock.Size = Security.BindStringInput(tbxSize.Text, SecurityLevel.Zero);
                            stock.WeightUnit = Security.BindStringInput(tbxWeightUnit.Text, SecurityLevel.Zero);
                            stock.WidthWholeNumberFirstDigit = Security.BindIntegerInput(tbxWidthWholeFirstDigit.Text, SecurityLevel.Zero);
                            stock.WidthWholeNumberSecondDigit = Security.BindIntegerInput(tbxWidthWholeSecondDigit.Text, SecurityLevel.Zero);
                            stock.WidthFractionNumberFirstDigit = Security.BindIntegerInput(tbxWidthFractionFirstDigit.Text, SecurityLevel.Zero);
                            stock.WidthFractionNumberSecondDigit = Security.BindIntegerInput(tbxWidthFractionSecondDigit.Text, SecurityLevel.Zero);
                            double widthFraction = 0.0;
                            if (stock.WidthFractionNumberSecondDigit > 0)
                            {
                                widthFraction = (double)stock.WidthFractionNumberFirstDigit / stock.WidthFractionNumberSecondDigit;
                            }
                            stock.WidthValue = (stock.WidthWholeNumberFirstDigit * 10 + stock.WidthWholeNumberSecondDigit) + widthFraction;
                            stock.WidthUnit = string.Empty;

                            stock.DiameterWholeNumberFirstDigit = Security.BindIntegerInput(tbxDiameterWholeFirstDigit.Text, SecurityLevel.Zero);
                            stock.DiameterWholeNumberSecondDigit = Security.BindIntegerInput(tbxDiameterWholeSecondDigit.Text, SecurityLevel.Zero);
                            stock.DiameterFractionNumberFirstDigit = Security.BindIntegerInput(tbxDiameterFractionFirstDigit.Text, SecurityLevel.Zero);
                            stock.DiameterFractionNumberSecondDigit = Security.BindIntegerInput(tbxDiameterFractionSecondDigit.Text, SecurityLevel.Zero);
                            double diaFraction = 0.0;
                            if (stock.DiameterFractionNumberSecondDigit > 0)
                            {
                                diaFraction = (double)stock.DiameterFractionNumberFirstDigit / stock.DiameterFractionNumberSecondDigit;
                            }
                            stock.DiameterValue = (stock.DiameterWholeNumberFirstDigit * 10 + stock.DiameterWholeNumberSecondDigit) + diaFraction;
                            stock.DiameterUnit = string.Empty;

                            stock.ThreadCountWholeNumberFirstDigit = Security.BindIntegerInput(tbxThreadCountWholeFirstDigit.Text, SecurityLevel.Zero);
                            stock.ThreadCountWholeNumberSecondDigit = Security.BindIntegerInput(tbxThreadCountWholeSecondDigit.Text, SecurityLevel.Zero);
                            stock.ThreadCountFractionNumberFirstDigit = Security.BindIntegerInput(tbxThreadCountFractionFirstDigit.Text, SecurityLevel.Zero);
                            stock.ThreadCountFractionNumberSecondDigit = Security.BindIntegerInput(tbxThreadCountFractionSecondDigit.Text, SecurityLevel.Zero);
                            double thrdFraction = 0.0;
                            if (stock.ThreadCountFractionNumberSecondDigit > 0)
                            {
                                thrdFraction = (double)stock.ThreadCountFractionNumberFirstDigit / stock.ThreadCountFractionNumberSecondDigit;
                            }
                            stock.ThreadCountValue = (stock.ThreadCountWholeNumberFirstDigit * 10 + stock.ThreadCountWholeNumberSecondDigit) + thrdFraction;

                            stock.ThreadCountUnit = string.Empty;

                            stock.LengthWholeNumberFirstDigit = Security.BindIntegerInput(tbxLengthWholeFirstDigit.Text, SecurityLevel.Zero);
                            stock.LengthWholeNumberSecondDigit = Security.BindIntegerInput(tbxLengthWholeSecondDigit.Text, SecurityLevel.Zero);
                            stock.LengthFractionNumberFirstDigit = Security.BindIntegerInput(tbxLengthFractionFirstDigit.Text, SecurityLevel.Zero);
                            stock.LengthFractionNumberSecondDigit = Security.BindIntegerInput(tbxLengthFractionSecondDigit.Text, SecurityLevel.Zero);
                            double lengthFraction = 0.0;
                            if (stock.LengthFractionNumberSecondDigit > 0)
                            {
                                lengthFraction = (double)stock.LengthFractionNumberFirstDigit / stock.LengthFractionNumberSecondDigit;
                            }
                            stock.LengthValue = (stock.LengthWholeNumberFirstDigit * 10 + stock.LengthWholeNumberSecondDigit) + lengthFraction;

                            stock.LengthUnit = string.Empty;

                            stock.Weight = Security.BindDoubleInput(tbxWeight.Text, SecurityLevel.Zero);
                            stock.StockAmount = Security.BindIntegerInput(tbxStock.Text, SecurityLevel.Zero);
                            stock.PkgQuanity = Security.BindIntegerInput(tbxPkgQuanity.Text, SecurityLevel.Zero);
                            if (imageUploaded)
                            {
                                product = Product.ChangeImageFile(tempImageFolder, product);
                                product.ProductImageUrl = product.ProductImageUrl;
                            }

                            product = product.Update();

                            this.CreateAdditionalImageForProduct(product.ProductId);

                            BindData(product);
                            BindAdditionalProductData(product.ProductId);

                            if (DeleteList.Count > 0)
                            {
                                TblPartnerProduct.DeleteTblPartnerProductList(DeleteList);
                            }

                            SaveAllPartnerWithPrice();
                            uccResponseMessage.SetSuccessMessage(AutoGearCommonMessage.ProductUpdateSuccessful);
                        }
                        catch (DuplicateException ex)
                        {
                            uccResponseMessage.SetFailMessage(ex.Message);
                        }
                        catch (InvalidOperationException ex)
                        {
                            uccResponseMessage.SetFailMessage(ex.Message);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ProductUpdateFailed);
        }
    }

    private void CreateAdditionalImageForProduct(int productId)
    {   
        for (int i = 1; i < Request.Files.Count; i++)
        {
            HttpPostedFile fuImageAdditional = Request.Files[i];

            if (fuImageAdditional.ContentLength > 0)
            {
                CreateAdditionalImageForProduct(productId, fuImageAdditional);
            }            
        }

        BindAdditionalProductData(productId);
    }

    private void CreateAdditionalImageForProduct(int productId, HttpPostedFile fuImageAdditional)
    {
        try
        {
            string tempImagePath = UploadTemporaryAdditionalImageFiles(fuImageAdditional);

            string realImagePath = ProductFileAccessUtility.UploadAdditionalImages(tempImagePath);

            TblProductAdditionalImage additional = new TblProductAdditionalImage();
            additional.ProductID = productId;
            additional.AdditionalImageUrl = realImagePath;
            additional.Save();
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    protected string UploadTemporaryAdditionalImageFiles(HttpPostedFile fuImageAdditional)
    {
        string tempImageFolder = string.Empty;
        if (fuImageAdditional.ContentLength > 0)
        {
            tempImageFolder = SiteUtility.TempFolder + Path.GetFileName(fuImageAdditional.FileName);

            if (File.Exists(MapPath(tempImageFolder)))
                FileAccessUtility.DeleteFile(tempImageFolder);

            string contentType = fuImageAdditional.ContentType.ToLower();
            if (contentType == "image/jpg" || contentType == "image/gif" || contentType == "image/png"
                || contentType == "image/jpeg" || contentType == "image/bmp" || contentType == "image/pjpeg"
                || contentType == "image/x-png")
            {
                fuImageAdditional.SaveAs(MapPath(tempImageFolder));
            }
        }

        return tempImageFolder;
    }

    protected void LoadDropDowns()
    {
        //ddlBrand.DataSource = ProductBrand.Brands(false);
        //ddlBrand.DataTextField = "BrandName";
        //ddlBrand.DataValueField = "ProductBrandId";
        //ddlBrand.DataBind();

        ddlParent.Items.Clear();
        ReadWriteCustomCollection<KeyValuePair<string, string>> productCategoryTree = CategoryManager.GetSubCategoryTree(SiteUtility.SuperRootCategoryId);
        foreach (KeyValuePair<string, string> productCategory in productCategoryTree)
        {
            ddlParent.Items.Add(new ListItem(productCategory.Key,Server.HtmlEncode(productCategory.Value)));
        }
    }
    //protected void btnExportImport_Click(object sender, EventArgs e)
    //{
    //    Response.Redirect(AutoGear.BLL.CustomSiteMap.ExportImport);
    //}
    protected void btnImageDelete_Click(object sender, EventArgs e)
    {
        int productId = 0;
        if (!string.IsNullOrEmpty(Request.QueryString["pid"]) &&
            int.TryParse(Request.QueryString["pid"], out productId))
        {
            Product product = Product.Load(productId);
            try
            {
                FileAccessUtility.DeleteFile(product.ProductImageUrl);
                FileAccessUtility.DeleteFile(product.ProductImageSmallThumbnail);
                FileAccessUtility.DeleteFile(product.ProductImageMaxSize);
                FileAccessUtility.DeleteFile(product.ProductImageLargeThumbnail);
                FileAccessUtility.DeleteFile(product.ProductImageDetailSize);
                divProductDefaultImagePreview.Visible = false;
            }
            catch { }
        }
    }
    
    private bool DeleteProductAdditionalImage(int id)
    {
        TblProductAdditionalImage additional = TblProductAdditionalImage.GetTblProductAdditionalImageByID(id);

        try
        {
            FileAccessUtility.DeleteFile(additional.AdditionalImageUrl);
            FileAccessUtility.DeleteFile(additional.AdditionalImageUrl.Replace("list", "smallthumb"));
            FileAccessUtility.DeleteFile(additional.AdditionalImageUrl.Replace("list", "max"));
            FileAccessUtility.DeleteFile(additional.AdditionalImageUrl.Replace("list", "largethumb"));
            FileAccessUtility.DeleteFile(additional.AdditionalImageUrl.Replace("list", "detail"));

            TblProductAdditionalImage.DeleteTblProductAdditionalImage(id);

            return true;
        }
        catch (Exception ex)
            {
            
            return false; 
        
        }
    }

    protected void rptAdditionalPreview_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (!String.IsNullOrEmpty(e.CommandArgument.ToString()))
        {
            int productAdditionalImageId = Convert.ToInt32(e.CommandArgument.ToString());

            if (DeleteProductAdditionalImage(productAdditionalImageId))
            {
                int productId = 0;
                if (!string.IsNullOrEmpty(Request.QueryString["pid"]) &&
                    int.TryParse(Request.QueryString["pid"], out productId))
                {
                    BindAdditionalProductData(productId);
                }
            }
        }    
    }

    protected void lnbAddNew_Click(object sender, EventArgs e)
    {
        ProductPartner newProd = new ProductPartner();
        newProd.BrandName = "";
        newProd.PartnerId = 1;
        newProd.PartnerProductId = -1;
        newProd.ProductId = _ProductId;
       
        partnerProducts.Add(newProd);
        repProductPartners.DataSource = partnerProducts;
        repProductPartners.DataBind();
       
    }
    protected void repProductPartners_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            ProductPartner newProd = e.Item.DataItem as ProductPartner;
            DropDownList ddlBrandName = e.Item.FindControl("ddlBrandName") as DropDownList;
            ddlBrandName.DataSource = brands;
            
            ddlBrandName.DataTextField = "BrandName";
            ddlBrandName.DataValueField = "ProductBrandId";
            ddlBrandName.DataBind();
            ddlBrandName.SelectedValue = newProd.PartnerId.ToString();
           
            
            
        }
    }

    private void SaveAllPartnerWithPrice()
    {
        foreach (RepeaterItem item in repProductPartners.Items)
        {

            HtmlInputHidden hidProdPartnerId = item.FindControl("hidProdPartnerId") as HtmlInputHidden;
            DropDownList ddlBrandName = item.FindControl("ddlBrandName") as DropDownList;
            TextBox txtProductionCost = item.FindControl("txtProductionCost") as TextBox;
            TextBox txtSellPrice = item.FindControl("txtSellPrice") as TextBox;
            if (hidProdPartnerId.Value != "-1")
            {
                TblPartnerProduct partnerProduct = TblPartnerProduct.GetTblPartnerProductByPartnerProductId(Convert.ToDecimal(hidProdPartnerId.Value));
                partnerProduct.PartnerId = Convert.ToInt32(ddlBrandName.SelectedItem.Value);
                partnerProduct.ProductionCost = Convert.ToDecimal(txtProductionCost.Text.Trim());
                partnerProduct.SellPrice = Convert.ToDecimal(txtSellPrice.Text.Trim());
                partnerProduct.Save();
            }
            else
            {
                TblPartnerProduct partnerProduct = new TblPartnerProduct();
                partnerProduct.ProductId = _ProductId;
                partnerProduct.ProductionCost = Convert.ToDecimal(txtProductionCost.Text.Trim());
                partnerProduct.PartnerId = Convert.ToInt32(ddlBrandName.SelectedItem.Value);
                partnerProduct.ProductionCost = Convert.ToDecimal(txtProductionCost.Text.Trim());
                partnerProduct.SellPrice = Convert.ToDecimal(txtSellPrice.Text.Trim());
                partnerProduct.Save();
            }
        }
    }
    protected void repProductPartners_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        String commandString = e.CommandArgument.ToString();
        String[] comParams = commandString.Split(new char[] { ':'});
        Int32 currentIndex = Convert.ToInt32(comParams[0]);
        if (comParams[1] != "-1")
        {
            DeleteList.Add(Convert.ToInt32(comParams[1]));
        }

        partnerProducts.RemoveAt(currentIndex);
        repProductPartners.DataSource = partnerProducts;
        repProductPartners.DataBind();
    }
}
